package cn.tpshion.devops.service.impl;

import cn.tpshion.devops.common.constant.RedisKey;
import cn.tpshion.devops.domain.dto.SecretDTO;
import cn.tpshion.devops.domain.entity.SecretData;
import cn.tpshion.devops.service.SecretService;
import cn.tpshion.devops.util.AssertUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SecretServiceImpl implements SecretService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<SecretData> secretList() {
        HashOperations<String, String, String> hash = redisTemplate.opsForHash();
        Map<String, String> map = hash.entries(RedisKey.SECRET);
        if(ObjectUtils.isEmpty(map)){
            return Collections.emptyList();
        }
        return map.values().stream().map(i -> {
            SecretData secretData = JSON.parseObject(i, SecretData.class);
            secretData.setData(null);
            return secretData;
        }).collect(Collectors.toList());
    }

    @Override
    public void addSecret(SecretData data) {
        HashOperations<String, String, String> hash = redisTemplate.opsForHash();
        AssertUtil.isTrue(hash.hasKey(RedisKey.SECRET, data.getName()), "密钥配置已存在");

        hash.put(RedisKey.SECRET, data.getName(), JSON.toJSONString(data));
    }

    @Override
    public void deleteSecret(SecretDTO dto) {
        HashOperations<String, String, String> hash = redisTemplate.opsForHash();
        hash.delete(RedisKey.SECRET, dto.getName());
    }
}
